import json
import pandas as pd

"""
alpaca sample
{
    "instruction": "今天的天气怎么样？", #指令输入，必填
    "input": "", #背景信息，选填
    "output": "今天的天气不错，是晴天。", #输出内容，必填
    "system": "", #系统提示词，选填
    "history": [ #历史会话，选填
      [
        "今天会下雨吗？",
        "今天不会下雨，是个好天气。"
      ],
      [
        "今天适合出去玩吗？",
        "非常适合，空气质量很好。"
      ]
    ]
}
"""


def trans_excel_to_alpaca(excel_file, sheet_name, json_file, instruction_column, output_column, input_column,
                          system_column, history_column):
    alpaca_data = []

    excel_data = pd.read_excel(excel_file, sheet_name=sheet_name)
    for index, row in excel_data.iterrows():
        data = {
            "instruction": excel_row_to_json(row, instruction_column),
            "input": excel_row_to_json(row, input_column),
            "output": excel_row_to_json(row, output_column),
            "system": excel_row_to_json(row, system_column),
            "history": excel_row_to_json(row, history_column)
        }
        alpaca_data.append(data)

    with open(json_file, 'w', encoding='utf-8') as file:
        json.dump(alpaca_data, file, ensure_ascii=False)


def excel_row_to_json(row, columns):
    data = {}
    for column in columns:
        data[column] = row[column]
    return json.dumps(data, ensure_ascii=False)
